import React, { useState, useEffect } from 'react';
import { Modal, Input, Typography } from 'antd';
import { SvgIcon } from '@/components/icon';
import BoxInfo from '@/components/box/boxInfo';
import { GetWorkBenhList } from '@/common';
import { MetahumanResource } from '@/types/metahuman';
import metahumanService from '@/api/services/metahumanService';
import Modals from '@/components/modals/Modals';

const { Text } = Typography;

interface MetahumanModalProps {
  open: boolean;
  onOk: (selectedApps: MetahumanResource[]) => void;
  onCancel: () => void;
  existingApps?: MetahumanResource[];
}

const MetahumanModal: React.FC<MetahumanModalProps> = ({
  open,
  onOk,
  onCancel,
  existingApps = [],
}) => {
  const [selectedApps, setSelectedApps] = useState<GetWorkBenhList[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const [defaultMaxConnections, setDefaultMaxConnections] = useState<number>(5);
  const [isConnectionModalVisible, setIsConnectionModalVisible] = useState<boolean>(false);
  const [tempConnections, setTempConnections] = useState<number>(5);
  const [connectionError, setConnectionError] = useState<string>('');
  const [maxConnectionLimit, setMaxConnectionLimit] = useState<number>(100);

  // 获取最大连接数限制
  useEffect(() => {
    const fetchConnectionLimit = async () => {
      try {
        const response = await metahumanService.getMetahumanConnectionLimit();
        setMaxConnectionLimit(response.limit);
      } catch (error) {
        console.error('获取连接限制失败:', error);
        // 如果API调用失败，使用默认值
        setMaxConnectionLimit(100);
      }
    };

    if (open) {
      fetchConnectionLimit();
    }
  }, [open]);

  const handleAppSelection = (selectedAppList: GetWorkBenhList[]) => {
    console.log('选中的应用:', selectedAppList);
    setSelectedApps(selectedAppList);
  };

  const validateConnectionLimit = (value: number): boolean => {
    if (value <= 0) {
      setConnectionError('连接数必须大于0');
      return false;
    }
    if (value > maxConnectionLimit) {
      setConnectionError('人数超过最大上限');
      return false;
    }
    setConnectionError('');
    return true;
  };

  const handleConnectionChange = (value: string) => {
    const numValue = Number(value);
    setTempConnections(numValue);
    validateConnectionLimit(numValue);
  };

  const handleEditConnections = () => {
    setIsConnectionModalVisible(true);
    setTempConnections(defaultMaxConnections);
    setConnectionError('');
  };

  const handleSaveConnections = () => {
    if (validateConnectionLimit(tempConnections)) {
      setDefaultMaxConnections(tempConnections);
      setIsConnectionModalVisible(false);
    }
  };

  const handleCancelEditConnections = () => {
    setIsConnectionModalVisible(false);
    setTempConnections(defaultMaxConnections);
    setConnectionError('');
  };

  const handleOk = () => {
    // 将选中的应用转换为 MetahumanResource 格式
    const newApps: MetahumanResource[] = selectedApps.map((app: any) => ({
      appId: app.app_id,
      appName: app.app_name,
      appDescription: app.app_description || '应用详情描述',
      appAvatar: app.app_logo || '',
      maxConnections: defaultMaxConnections, // 使用设置的默认连接上限
      activeConnections: 0,
    }));

    // 合并现有应用和新选择的应用，去重
    const allApps = [...existingApps, ...newApps];
    const uniqueApps = allApps.filter(
      (app, index, self) => index === self.findIndex((a) => a.appId === app.appId),
    );

    onOk(uniqueApps);
    setSelectedApps([]);
    setSearchText('');
    // message.success(`成功添加 ${newApps.length} 个应用`);
  };

  const handleCancel = () => {
    setSelectedApps([]);
    setSearchText('');
    onCancel();
  };

  // 将现有应用转换为 BoxInfo 需要的格式
  const existingAppList = existingApps.map((app) => ({
    id: app.appId,
    name: app.appName,
    description: app.appDescription,
    icon: app.appAvatar,
  }));

  return (
    <Modal
      title="选择要开启数字人的应用"
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      width={1000}
      okText={`添加${Math.max(selectedApps.length, 0)}个应用`}
      cancelText="取消"
      okButtonProps={{
        disabled: selectedApps.length === 0,
      }}
      destroyOnHidden={true}
      footer={[
        <div
          key="footer"
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            width: '100%',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <Text style={{ fontSize: '14px', color: '#5E6772' }}>
              每个应用可连接人数: {defaultMaxConnections}
            </Text>
            <Text
              style={{
                fontSize: '14px',
                color: '#1890FF',
                cursor: 'pointer',
                textDecoration: 'underline',
              }}
              onClick={handleEditConnections}
            >
              修改
            </Text>
          </div>
          <div>
            <button
              key="cancel"
              onClick={handleCancel}
              style={{
                marginRight: 8,
                padding: '4px 15px',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                background: '#fff',
                cursor: 'pointer',
              }}
            >
              取消
            </button>
            <button
              key="submit"
              onClick={handleOk}
              disabled={selectedApps.length === 0}
              style={{
                padding: '4px 15px',
                border: '1px solid #1890ff',
                borderRadius: '6px',
                background: '#1890ff',
                color: '#fff',
                cursor: selectedApps.length === 0 ? 'not-allowed' : 'pointer',
                opacity: selectedApps.length === 0 ? 0.5 : 1,
              }}
            >
              添加{Math.max(selectedApps.length, 0)}个应用
            </button>
          </div>
        </div>,
      ]}
    >
      <div className="mb-4 flex justify-end">
        <Input
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          className="!rounded-md"
          style={{
            height: '32px',
            width: '200px',
          }}
          placeholder="请输入应用名称"
          suffix={<SvgIcon icon="work-ic6" size={16} />}
        />
      </div>

      <BoxInfo
        searchText={searchText}
        isMultiSelect={2}
        paramsType="public"
        appType="agent,workflow"
        confirm={handleAppSelection}
        selectApps={existingAppList}
      />

      {/* 设置数字人连接数量弹窗 */}
      <Modals
        title="设置每个应用可连接人数"
        open={isConnectionModalVisible}
        onOk={handleSaveConnections}
        onCancel={handleCancelEditConnections}
        okText="确定"
        cancelText="取消"
        width={400}
      >
        <div style={{ padding: '0' }}>
          <div style={{ marginBottom: '12px' }}>
            <Text style={{ fontSize: '14px', color: '#5E6772' }}>
              连接上限（人）
              {/* {maxConnectionLimit} */}
            </Text>
          </div>
          <Input
            type="number"
            value={tempConnections}
            onChange={(e) => handleConnectionChange(e.target.value)}
            min={1}
            max={maxConnectionLimit}
            // style={{
            //   width: '100%',
            //   borderColor: connectionError ? '#ff4d4f' : undefined
            // }}
            className={`w-full ${connectionError ? 'border-red-600 border' : ''}`}
            placeholder="请输入连接上限"
          />
          {connectionError && (
            <Text
              style={{ fontSize: '12px', color: '#ff4d4f', marginTop: '8px', display: 'block' }}
            >
              {connectionError}
            </Text>
          )}
        </div>
      </Modals>
    </Modal>
  );
};

export default MetahumanModal;
